﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using System.Collections;
using Microsoft.SharePoint.Utilities;
using System.Globalization;

namespace MS.InformationManagement.Core.AdministracionDeUsuarios
{
    public class AdministracionDeUsuarios
    {
        #region Public Methods

        public void BreakPermissionLibrary(Guid ListID)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            SPList list = web.Lists.GetList(ListID, true);
                            list.BreakRoleInheritance(false, false);
                            SPRoleAssignmentCollection roleAssigns = list.RoleAssignments;
                            for (int i = roleAssigns.Count - 1; i >= 0; i--)
                            {
                                roleAssigns.Remove(i);
                            }
                            list.Update();
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }   
        }

        public void AddPermissionLibrary(Guid ListID, string Seccion)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;

                            SPList list = web.Lists.GetList(ListID, true);
                            ArrayList GroupsList = new ArrayList();
                            GetParentsSeccion(Seccion, GroupsList);

                            foreach (string str in GroupsList)
                            {
                                list.ForceCheckout = false;
                                SPRoleDefinition oRole = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                                SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteGroups[str]);
                                roleAssignment.RoleDefinitionBindings.Add(oRole);
                                list.RoleAssignments.Add(roleAssignment);
                                list.Update();
                            }
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }            
        }

        public Array GetUsersFromSeccion(string Seccion)
        {
            ArrayList AllUsersList = new ArrayList();
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;

                            ArrayList GroupsList = new ArrayList();
                            GetChildSeccion(Seccion.ToUpper(), GroupsList);

                            foreach (string str in GroupsList)
                            {
                                SPGroup WebGroup = web.SiteGroups[str];
                                if (WebGroup != null)
                                {
                                    foreach (SPUser user in WebGroup.Users)
                                    {
                                        string userName = user.LoginName;
                                        string libraryName = userName.Substring(userName.LastIndexOf('\\') + 1);
                                        AllUsersList.Add(libraryName);
                                    }
                                }
                            }
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
            var Consulta = (from string t in AllUsersList select t).Distinct();
            return Consulta.ToArray();
        }

        private static ArrayList GetParentsSeccion(string Seccion, ArrayList GruposList)
        {
            string CamlQuery = "<Where><Eq><FieldRef Name='" + SPBuiltInFieldId.Title + "'/><Value Type='Text'>" + Seccion + "</Value></Eq></Where>";
            SPQuery query = new SPQuery();
            query.Query = CamlQuery;

            string recorsSiteUrl = SPContext.Current.Web.Url;//ConfigurationHelper.GetInstance().ConfigItems[GlobalConstants.SITE_RECORDS_URL];

            using (SPSite recordsSite = new SPSite(recorsSiteUrl))
            {
                using (SPWeb recordsWeb = recordsSite.OpenWeb())
                {
                    SPList ListSecciones = recordsWeb.Lists.TryGetList(GlobalConstants.LIST_BIBLIOTECA_SECCION);
                    SPListItemCollection listColl = ListSecciones.GetItems(query);
                    if (listColl.Count > 0)
                    {
                        SPFieldLookupValue spGroup = new SPFieldLookupValue(listColl[0][CustomSiteColumns.FIELD_SECURITY_GROUP_INTERNAL_NAME].ToString());
                        GruposList.Add(spGroup.LookupValue);
                        string SeccionPadre = listColl[0][CustomSiteColumns.FIELD_SECCION_PADRE_INTERNAL_NAME] + "";
                        if (!string.IsNullOrEmpty(SeccionPadre.Trim()))
                        {
                            SPFieldLookupValue spv = new SPFieldLookupValue(SeccionPadre);
                            return GetParentsSeccion(spv.LookupValue, GruposList);
                        }
                    }
                }
            }
            return GruposList;
        }

        private static Array GetChildSeccion(string Seccion, ArrayList GruposList)
        {
            GruposList.Add(Seccion);

            string CamlQuery = "<Where><Eq><FieldRef Name='" + "Secci_x00f3_n_x0020_Padre" + "'/><Value Type='Text'>" + Seccion + "</Value></Eq></Where>";
            SPQuery query = new SPQuery();
            query.Query = CamlQuery;

            string recorsSiteUrl = SPContext.Current.Web.Url;// ConfigurationHelper.GetInstance().ConfigItems[GlobalConstants.SITE_RECORDS_URL];

            using (SPSite recordsSite = new SPSite(recorsSiteUrl))
            {
                using (SPWeb recordsWeb = recordsSite.OpenWeb())
                {
                    SPList ListSecciones = recordsWeb.Lists.TryGetList(GlobalConstants.LIST_BIBLIOTECA_SECCION);
                    SPListItemCollection listColl = ListSecciones.GetItems(query);
                    if (listColl.Count > 0)
                    {
                        foreach (SPListItem item in listColl)
                        {
                            string title = item.Title.ToString();
                            if (!string.IsNullOrEmpty(title.Trim()))
                            {
                                GetChildSeccion(title, GruposList);
                            }
                        }
                    }
                }
            }
            var Consulta = (from string t in GruposList select t).Distinct();

            return Consulta.ToArray();
        }

        private static bool GetLibrary(SPUser User)
        {
            bool result = false;
            string userName = User.LoginName;
            string libraryName = userName.Substring(userName.LastIndexOf('\\') + 1);
            SPList targetLibrary = SPContext.Current.Web.Lists.TryGetList(libraryName);
            if (targetLibrary != null)
            {
                result = true;
            }

            return result;
        }

        #endregion
    }
}
